package com.wen.yygh.msm.controller;

import com.wen.yygh.common.result.Result;
import com.wen.yygh.common.utils.RedisUtil;
import com.wen.yygh.msm.service.MsmService;
import com.wen.yygh.msm.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Wenjl
 */
@RestController
@RequestMapping("api/msm")
@Api(tags = "短信验证码")
public class MsmController {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private MsmService msmService;

    @GetMapping("send/{phone}")
    @ApiOperation("发送验证码")
    public Result send(@PathVariable("phone") String phone) {
        //从redis获取验证码，如果获取获取到，返回ok
        String code = (String) redisUtil.get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        //如果从redis获取不到，
        // 生成验证码，
        code = RandomUtil.getSixBitRandom();
        //调用service方法，通过整合短信服务进行发送
        boolean isSend = msmService.send(phone, code);
        //生成验证码放到redis里面，设置有效时间
        if (isSend) {

            redisUtil.set(phone, code, 5 * 60);
            return Result.ok();
        } else {
            return Result.fail().message("发送短信失败");
        }
    }
}

